<template>
	<uni-popup ref="popup" type="center">
		<view class="dialog" :mask-click="false">
			<view class="title"> 尚未登录，是否登录?</view>
			<button type="default" open-type="getUserInfo" @getuserinfo="getUserInfo" class="login" size="mini">授权登录</button>
			<button class="close" @click="$emit('close')"></button>
		</view>
	</uni-popup>
</template>

<script>
import { login } from "../api/wxuser.js";
import { setCache } from "../util/index.js";

export default {
	mounted() {
		this.$refs.popup.open();
		this.getLoginCode();
	},
	methods: {
		getLoginCode() {
			return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					timeout: 5e3,
					success: resolve,
					fail: reject,
				});
			}).then(({ code, errMsg }) => {
				console.warn(code, errMsg);
				this.code = code;
			}).catch(() => {
				return this.getLoginCode();
			});
		},
		getUserInfo(e) {
			console.log(e);
			if (!this.code) {
				return uni.showToast({
					title: "请重试登录"
				});
			}
			uni.showLoading();
			login({
				code: this.code,
				encrypted_data: e.detail.encryptedData,
				raw_data: e.detail.rawData,
				signature: e.detail.signature,
				iv: e.detail.iv,
			}).then(({ token, user }) => {
				setCache('token', token).catch(console.warn);
				setCache('user_info', user).catch(console.warn);
				uni.showToast({
					title: "登录成功"
				});
				this.$emit('success');
			}).catch((err) => {
				uni.showToast({
					title: err
				});
			}).finally(() => {
				uni.hideLoading();
			});
		},
	}
}
</script>

<style lang="scss" scoped>
.dialog {
	width: 70vw;
	height: 60vw;
	background-color: white;
	border-radius: 15rpx;
	position: relative;
	text-align: center;
}
.title {
	text-align: center;
	padding-top: 90rpx;
}
.close {
	position: absolute;
	right: 30rpx;
	top: 30rpx;
	width: 40rpx;
	height: 40rpx;
	background-image: url("../static/image/close.png");
	background-repeat: no-repeat;
	background-size: 100% 100%;
	border: none;
	outline: none;
	padding: 0;
}

.close::after {
	display: none;
}

.login {
	margin-top: 60rpx;
}
</style>